import socketOfflineAllApi from '@/api/socket/socketOfflineAllApi'
import socketOfflineByIdSetApi from '@/api/socket/socketOfflineByIdSetApi'
import socketPageApi from '@/api/socket/socketPageApi'
import { checkIdSet } from '@/components/CAddOrderNo/CAddOrderNo'
import CSearchForm from '@/components/CSearchForm/CSearchForm'
import CTable from '@/components/CTable/CTable'
import { IMyOrderItem } from '@/model/form/common/IMyPage'
import ISocketPageForm from '@/model/form/socket/ISocketPageForm'
import ISocketPageVO from '@/model/vo/socket/ISocketPageVO'
import IUserPageVO from '@/model/vo/user/IUserPageVO'
import { execConfirm, ToastSuccess } from '@/util/CommonUtil'
import { updateTimeOrder } from '@/util/http'
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons'
import { Badge, Button, ButtonGroup, Dropdown, Space } from '@douyinfe/semi-ui'
import { ChangeInfoSorter } from '@douyinfe/semi-ui/lib/es/table'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
import OnlineUserColumns from './OnlineUserColumns'
import OnlineUserSearchFormItem, {
  getOnlineUserSearchFormSelectData,
} from './OnlineUserSearchFormItem'

export default function User() {
  const [selectedRowKeyList, setSelectedRowKeyList] = useState<
    (string | number)[]
  >([]) // 表格选中的 key集合
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<ISocketPageVO[]>([])
  const [sideSheetVisible, setSideSheetVisible] = useState(false) // 搜索 sideSheet是否显示
  const [searchForm, setSearchForm] = useState<ISocketPageForm>({}) // 搜索表单初始值

  const [total, setTotal] = useState(0)
  const [pageNum, setPageNum] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [sorter, setSorter] = useState<ChangeInfoSorter<any>>()

  // 执行获取 table数据
  function doGetTableData() {
    getTableData(
      setDataSource,
      setLoading,
      searchForm,
      pageNum,
      pageSize,
      setTotal,
      sorter
    )
  }

  const { dictList, userList } =
    getOnlineUserSearchFormSelectData(sideSheetVisible)

  useEffect(() => {
    doGetTableData()
  }, [])

  return (
    <div className="p-l-r-20">
      <CSearchForm
        sideSheetVisible={sideSheetVisible}
        setSideSheetVisible={setSideSheetVisible}
        getTableData={(values: any) => {
          setPageNum(1) // 这里的值不会立即生效
          setPageSize(10) // 这里的值不会立即生效
          getTableData(
            setDataSource,
            setLoading,
            values,
            1,
            10,
            setTotal,
            sorter
          )
        }}
        setSearchForm={setSearchForm}
      >
        <OnlineUserSearchFormItem
          dictList={dictList}
          userList={userList}
        ></OnlineUserSearchFormItem>
      </CSearchForm>

      <div className="flex jc-sb m-t-b-10">
        <Space>
          <Button
            theme="solid"
            onClick={() => {
              offlineAllClick(doGetTableData)
            }}
          >
            全部强退
          </Button>
          <Button
            theme="solid"
            type="danger"
            onClick={() => {
              if (!checkIdSet(selectedRowKeyList)) {
                return
              }
              offlineByIdSetClick(selectedRowKeyList, doGetTableData)
            }}
          >
            强退
          </Button>
        </Space>

        {/* @ts-ignore */}
        <ButtonGroup>
          <Button
            onClick={() => {
              setSideSheetVisible(true)
            }}
            icon={
              <Badge dot={Object.keys(searchForm).length !== 0} type="warning">
                <IconSearch title="搜索" className="flex ai-c" />
              </Badge>
            }
          ></Button>
          <Button
            onClick={() => {
              if (!loading) {
                doGetTableData()
              }
            }}
            disabled={loading}
            icon={<IconRefresh spin={loading} title="刷新" />}
          ></Button>
        </ButtonGroup>
      </div>

      <CTable<IUserPageVO>
        onChange={({ sorter }) => {
          setSorter(sorter)
          getTableData(
            setDataSource,
            setLoading,
            searchForm,
            pageNum,
            pageSize,
            setTotal,
            sorter
          )
        }}
        columns={OnlineUserColumns(dictList)}
        dataSource={dataSource}
        loading={loading}
        selectedRowKeyList={selectedRowKeyList}
        setSelectedRowKeyList={setSelectedRowKeyList}
        pagination={{
          total,
          currentPage: pageNum,
          pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setPageNum(currentPage) // 这里的值不会立即生效
            setPageSize(pageSize) // 这里的值不会立即生效
            getTableData(
              setDataSource,
              setLoading,
              searchForm,
              currentPage,
              pageSize,
              setTotal,
              sorter
            )
          },
          showSizeChanger: true,
        }}
        defaultOperateClickFun={(text, record, index) => {
          offlineByIdSetClick([record.id], doGetTableData)
        }}
        operateDropdownItem={(text, record, index) => (
          <>
            <Dropdown.Item
              className="red"
              onClick={() => {
                offlineByIdSetClick([record.id], doGetTableData)
              }}
            >
              强退
            </Dropdown.Item>
          </>
        )}
      ></CTable>
    </div>
  )
}

// 获取 table数据
function getTableData(
  setDataSource: Dispatch<SetStateAction<ISocketPageVO[]>>,
  setLoading: Dispatch<SetStateAction<boolean>>,
  searchForm: ISocketPageForm,
  pageNum: number,
  pageSize: number,
  setTotal: Dispatch<SetStateAction<number>>,
  sorter: ChangeInfoSorter<any> | undefined
) {
  setLoading(true)
  socketPageApi({
    ...searchForm,
    pageNum,
    pageSize,
    orderList: sorter?.sortOrder
      ? [{ name: sorter.dataIndex, value: sorter.sortOrder }, updateTimeOrder]
      : [updateTimeOrder],
    enableFlag: true, // 只要连接中的 socket
  })
    .then(({ data }) => {
      setDataSource(data.data.records)
      setTotal(data.data.total)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}

// 点击：全部强退
function offlineAllClick(doGetTableData: () => void) {
  execConfirm(
    () => {
      return socketOfflineAllApi().then(({ data }) => {
        ToastSuccess(data.msg)
        doGetTableData()
      })
    },
    undefined,
    '确定【全部强退】吗？'
  )
}

// 点击：强退
function offlineByIdSetClick(
  selectedRowKeyList: (string | number)[],
  doGetTableData: () => void
) {
  execConfirm(
    () => {
      return socketOfflineByIdSetApi({ idSet: selectedRowKeyList }).then(
        ({ data }) => {
          ToastSuccess(data.msg)
          doGetTableData()
        }
      )
    },
    undefined,
    '确定【强退】所选项吗？'
  )
}
